<template>
  <div class="git-operations-container">
    <div class="git-operations-header">
      <h3>Git 仓库操作</h3>
      <div class="repo-path">
        <span>仓库路径: </span>
        <template v-if="repoPath">
          <el-tag size="medium" class="repo-path-tag">{{ repoPath }}</el-tag>
          <el-button type="primary" size="small" @click="refreshStatus" :loading="isLoading">刷新状态</el-button>
          <el-tooltip effect="dark" placement="bottom">
            <template #content>
              <div>
                <p><strong>支持以下格式的仓库路径:</strong></p>
                <ul>
                  <li>本地仓库路径: C:/path/to/repo</li>
                  <li>远程仓库URL: https://gitee.com/username/repo.git</li>
                </ul>
                <p>注意: 使用远程URL时，需确保已在本地克隆该仓库</p>
              </div>
            </template>
            <el-button type="info" size="small" circle>?</el-button>
          </el-tooltip>
        </template>
        <el-alert
          v-else
          title="未设置项目Git仓库路径"
          type="warning"
          description="此任务所属项目未设置Git仓库路径，请在项目设置中配置Git仓库信息。"
          show-icon
          :closable="false"
        />
      </div>
    </div>
    
    <div class="git-quick-actions">
      <el-button-group>
        <el-button type="primary" size="small" @click="handleGitAddAll" :loading="isLoading">
          <el-icon><Plus /></el-icon> 暂存所有
        </el-button>
        <el-button type="success" size="small" @click="showCommitDialog" :loading="isLoading">
          <el-icon><Check /></el-icon> 提交
        </el-button>
        <el-button type="warning" size="small" @click="handleGitPush" :loading="isLoading">
          <el-icon><Upload /></el-icon> 推送
        </el-button>
        <el-button type="info" size="small" @click="handleGitPull" :loading="isLoading">
          <el-icon><Download /></el-icon> 拉取
        </el-button>
      </el-button-group>
    </div>
    
    <el-tabs v-model="activeTab" class="git-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="状态" name="status">
        <div class="git-status" v-loading="isLoading">
          <el-alert
            v-if="statusError"
            :title="statusError"
            type="error"
            show-icon
            :closable="false"
          >
            <template v-if="statusError.includes('仓库路径不存在') || statusError.includes('无效的Git仓库')" #default>
              <p>解决方案：</p>
              <ul>
                <li>确保您的本地路径正确，并且该目录已经初始化为Git仓库</li>
                <li>如果您需要使用远程仓库，请确保先将其克隆到本地，并在项目设置中更新本地仓库路径</li>
                <li>本地路径末尾的.git后缀会被自动处理，无需手动删除</li>
              </ul>
              <div class="clone-action">
                <el-button type="primary" size="small" @click="showCloneDialog">
                  克隆到本地
                </el-button>
              </div>
            </template>
          </el-alert>
          <pre v-else-if="statusOutput" class="status-output">{{ statusOutput }}</pre>
          <el-empty v-else description="暂无Git状态信息" />
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="分支" name="branch">
        <div class="git-branch" v-loading="isLoading">
          <div class="branch-actions">
            <el-select v-model="selectedBranch" placeholder="选择分支" size="small">
              <el-option
                v-for="branch in branchList"
                :key="branch.name"
                :label="branch.name"
                :value="branch.name"
              />
            </el-select>
            <el-button type="primary" size="small" @click="handleGitCheckout" :loading="isLoading" :disabled="!selectedBranch">
              切换分支
            </el-button>
            <el-button size="small" @click="loadBranches" :loading="isLoading">
              刷新分支
            </el-button>
          </div>
          <pre v-if="branchOutput" class="branch-output">{{ branchOutput }}</pre>
          <el-empty v-else description="暂无分支信息" />
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="历史" name="log">
        <div class="git-log" v-loading="isLoading">
          <el-button size="small" @click="loadCommitHistory" :loading="isLoading">
            刷新提交历史
          </el-button>
          <el-empty v-if="!commitHistory.length" description="暂无提交历史" />
          <el-timeline v-else>
            <el-timeline-item
              v-for="(commit, index) in commitHistory"
              :key="index"
              :timestamp="commit.date"
              :type="index === 0 ? 'primary' : ''"
            >
              <div class="commit-message">{{ commit.message }}</div>
              <div class="commit-details">
                <el-tag size="small">{{ commit.hash }}</el-tag>
                <span class="commit-author">{{ commit.author }}</span>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 提交对话框 -->
    <el-dialog
      v-model="commitDialogVisible"
      title="提交更改"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="commitForm" ref="commitFormRef" :rules="commitRules">
        <el-form-item label="提交信息" prop="message">
          <el-input
            v-model="commitForm.message"
            type="textarea"
            :rows="3"
            placeholder="请输入提交信息"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="commitForm.addAll">添加所有更改后提交</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="commitDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleGitCommit" :loading="isLoading">
            确认提交
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 克隆仓库对话框 -->
    <el-dialog
      v-model="cloneDialogVisible"
      title="克隆远程仓库"
      width="50%"
    >
      <el-form :model="cloneForm" ref="cloneFormRef">
        <el-form-item label="远程仓库URL" prop="url">
          <el-input 
            v-model="cloneForm.url" 
            placeholder="请输入远程仓库URL，例如：https://gitee.com/username/repo.git"
            :disabled="gitUrlDisabled"
          />
        </el-form-item>
        <p class="dialog-tip">
          仓库将被克隆到项目配置的本地路径下：<strong>{{ repoPath }}</strong>
        </p>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="cloneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleGitClone" :loading="isLoading">
            开始克隆
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 操作结果通知 -->
    <el-dialog
      v-model="resultDialogVisible"
      :title="resultDialogTitle"
      width="50%"
    >
      <div v-if="operationResult && operationResult.success" class="result-success">
        <el-icon class="result-icon success"><CircleCheck /></el-icon>
        <div class="result-message">{{ operationResult.message }}</div>
      </div>
      <div v-else-if="operationResult" class="result-error">
        <el-icon class="result-icon error"><CircleClose /></el-icon>
        <div class="result-message">{{ operationResult.message }}</div>
      </div>
      <div v-if="operationResult && operationResult.data" class="result-details">
        <div v-if="operationResult.data.stdout" class="result-stdout">
          <h4>输出:</h4>
          <pre>{{ operationResult.data.stdout }}</pre>
        </div>
        <div v-if="operationResult.data.stderr" class="result-stderr">
          <h4>错误输出:</h4>
          <pre>{{ operationResult.data.stderr }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, onUnmounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getGitStatus, 
  gitAddAll, 
  gitCommit, 
  gitCommitAll, 
  gitPush, 
  gitPull, 
  gitBranch,
  gitCheckout,
  gitLog,
  gitClone
} from '../api/gitService';
import { Plus, Check, Upload, Download, CircleCheck, CircleClose } from '@element-plus/icons-vue';

export default {
  name: 'GitOperations',
  components: {
    Plus,
    Check,
    Upload,
    Download,
    CircleCheck,
    CircleClose
  },
  props: {
    defaultRepoPath: {
      type: String,
      default: ''
    },
    taskId: {
      type: Number,
      default: null
    },
    gitRepoUrl: {
      type: String,
      default: ''
    },
    projectId: {
      type: Number,
      default: null
    }
  },
  emits: ['git-operation-completed'],
  setup(props, { emit }) {
    console.log('GitOperations setup - 接收到的props:', props);
    
    // 计算属性，防止直接访问props.gitRepoUrl可能导致的错误
    const gitUrlDisabled = computed(() => {
      return !!props?.gitRepoUrl;
    });
    
    // 只使用从父组件传递的仓库路径，不再使用本地存储
    const repoPath = ref(props?.defaultRepoPath || '');
    const isLoading = ref(false);
    const statusOutput = ref('');
    const statusError = ref('');
    const activeTab = ref('status');
    const branchList = ref([]);
    const selectedBranch = ref('');
    const branchOutput = ref('');
    const commitHistory = ref([]);
    const commitDialogVisible = ref(false);
    const resultDialogVisible = ref(false);
    const resultDialogTitle = ref('操作结果');
    const operationResult = ref(null);
    
    // 克隆仓库相关
    const cloneDialogVisible = ref(false);
    const cloneForm = reactive({
      url: props?.gitRepoUrl || ''
    });
    const cloneFormRef = ref(null);
    
    const commitForm = reactive({
      message: '',
      addAll: true
    });
    
    const commitRules = {
      message: [{ required: true, message: '请输入提交信息', trigger: 'blur' }]
    };
    
    const commitFormRef = ref(null);
    
    // 监听defaultRepoPath的变化
    watch(() => props?.defaultRepoPath, (newPath) => {
      if (newPath && newPath !== repoPath.value) {
        console.log('GitOperations: 仓库路径更新为', newPath);
        repoPath.value = newPath;
        // 如果路径改变且不为空，自动刷新状态
        if (newPath) {
          refreshStatus();
        }
      }
    }, { immediate: true });  // 立即执行一次监听函数
    
    // 监听gitRepoUrl的变化
    watch(() => props?.gitRepoUrl, (newRepoUrl) => {
      console.log('GitOperations: 仓库URL更新为', newRepoUrl);
      if (newRepoUrl) {
        // 如果URL更新了，同步更新克隆表单
        cloneForm.url = newRepoUrl;
      }
    }, { immediate: true });
    
    // 刷新Git状态
    const refreshStatus = async () => {
      if (!repoPath.value) {
        ElMessage.warning('请输入有效的仓库路径');
        return;
      }
      
      isLoading.value = true;
      statusError.value = '';
      statusOutput.value = '';
      
      try {
        const response = await getGitStatus(repoPath.value, props.projectId);
        if (response.data.success) {
          statusOutput.value = response.data.data.stdout;
        } else {
          statusError.value = response.data.message;
        }
      } catch (error) {
        statusError.value = `获取Git状态失败: ${error.message}`;
        console.error('获取Git状态失败:', error);
      } finally {
        isLoading.value = false;
      }
    };
    
    // 添加所有更改到暂存区
    const handleGitAddAll = async () => {
      if (!repoPath.value) {
        ElMessage.warning('请输入有效的仓库路径');
        return;
      }
      
      isLoading.value = true;
      
      try {
        const response = await gitAddAll(repoPath.value, props.projectId);
        showOperationResult('添加更改结果', response.data);
        
        // 操作完成后刷新状态
        if (response.data.success) {
          refreshStatus();
        }
        
        emit('git-operation-completed', {
          operation: 'add-all',
          success: response.data.success,
          message: response.data.message
        });
      } catch (error) {
        showOperationResult('添加更改结果', {
          success: false,
          message: `操作失败: ${error.message}`,
          data: null
        });
        console.error('Git add操作失败:', error);
      } finally {
        isLoading.value = false;
      }
    };
    
    // 显示提交对话框
    const showCommitDialog = () => {
      if (!repoPath.value) {
        ElMessage.warning('请输入有效的仓库路径');
        return;
      }
      
      commitForm.message = '';
      commitForm.addAll = true;
      commitDialogVisible.value = true;
    };
    
    // 显示克隆对话框
    const showCloneDialog = () => {
      // 优先使用传入的Git仓库URL
      cloneForm.url = props?.gitRepoUrl || repoPath.value || '';
      cloneDialogVisible.value = true;
    };
    
    // 提交更改
    const handleGitCommit = async () => {
      if (!commitFormRef.value) return;
      
      await commitFormRef.value.validate(async (valid) => {
        if (!valid) return;
        
        isLoading.value = true;
        commitDialogVisible.value = false;
        
        try {
          let response;
          
          if (commitForm.addAll) {
            response = await gitCommitAll(repoPath.value, commitForm.message, props.projectId);
          } else {
            response = await gitCommit(repoPath.value, commitForm.message, props.projectId);
          }
          
          showOperationResult('提交结果', response.data);
          
          // 操作完成后刷新状态和提交历史
          if (response.data.success) {
            refreshStatus();
            if (activeTab.value === 'log') {
              loadCommitHistory();
            }
          }
          
          emit('git-operation-completed', {
            operation: 'commit',
            success: response.data.success,
            message: response.data.message
          });
        } catch (error) {
          showOperationResult('提交结果', {
            success: false,
            message: `提交失败: ${error.message}`,
            data: null
          });
          console.error('Git commit操作失败:', error);
        } finally {
          isLoading.value = false;
        }
      });
    };
    
    // 推送更改到远程仓库
    const handleGitPush = async () => {
      if (!repoPath.value) {
        ElMessage.warning('请输入有效的仓库路径');
        return;
      }
      
      try {
        await ElMessageBox.confirm(
          '确定要推送更改到远程仓库吗?',
          '推送确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        isLoading.value = true;
        const response = await gitPush(repoPath.value, 'origin', null, props.projectId);
        showOperationResult('推送结果', response.data);
        
        emit('git-operation-completed', {
          operation: 'push',
          success: response.data.success,
          message: response.data.message
        });
      } catch (error) {
        if (error !== 'cancel') {
          showOperationResult('推送结果', {
            success: false,
            message: `推送失败: ${error.message || error}`,
            data: null
          });
          console.error('Git push操作失败:', error);
        }
      } finally {
        isLoading.value = false;
      }
    };
    
    // 从远程仓库拉取更改
    const handleGitPull = async () => {
      if (!repoPath.value) {
        ElMessage.warning('请输入有效的仓库路径');
        return;
      }
      
      isLoading.value = true;
      
      try {
        const response = await gitPull(repoPath.value, 'origin', null, props.projectId);
        showOperationResult('拉取结果', response.data);
        
        // 操作完成后刷新状态
        if (response.data.success) {
          refreshStatus();
        }
        
        emit('git-operation-completed', {
          operation: 'pull',
          success: response.data.success,
          message: response.data.message
        });
      } catch (error) {
        showOperationResult('拉取结果', {
          success: false,
          message: `拉取失败: ${error.message}`,
          data: null
        });
        console.error('Git pull操作失败:', error);
      } finally {
        isLoading.value = false;
      }
    };
    
    // 加载分支列表
    const loadBranches = async () => {
      if (!repoPath.value) {
        ElMessage.warning('请输入有效的仓库路径');
        return;
      }
      
      isLoading.value = true;
      branchOutput.value = '';
      branchList.value = [];
      
      try {
        const response = await gitBranch(repoPath.value);
        
        if (response.data.success) {
          branchOutput.value = response.data.data.stdout;
          
          // 解析分支输出
          const branches = response.data.data.stdout.split('\n').filter(Boolean);
          branchList.value = branches.map(branch => {
            const isActive = branch.startsWith('*');
            const name = branch.replace(/^\*\s+/, '').trim();
            return { name, isActive };
          });
          
          // 设置当前选中的分支
          const currentBranch = branchList.value.find(b => b.isActive);
          if (currentBranch) {
            selectedBranch.value = currentBranch.name;
          }
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        ElMessage.error(`获取分支失败: ${error.message}`);
        console.error('获取分支失败:', error);
      } finally {
        isLoading.value = false;
      }
    };
    
    // 切换分支
    const handleGitCheckout = async () => {
      if (!repoPath.value || !selectedBranch.value) {
        ElMessage.warning('请输入有效的仓库路径和选择分支');
        return;
      }
      
      isLoading.value = true;
      
      try {
        const response = await gitCheckout(repoPath.value, selectedBranch.value, props.projectId);
        showOperationResult('切换分支结果', response.data);
        
        // 操作完成后刷新分支和状态
        if (response.data.success) {
          loadBranches();
          refreshStatus();
        }
        
        emit('git-operation-completed', {
          operation: 'checkout',
          success: response.data.success,
          message: response.data.message
        });
      } catch (error) {
        showOperationResult('切换分支结果', {
          success: false,
          message: `切换分支失败: ${error.message}`,
          data: null
        });
        console.error('Git checkout操作失败:', error);
      } finally {
        isLoading.value = false;
      }
    };
    
    // 加载提交历史
    const loadCommitHistory = async () => {
      if (!repoPath.value) {
        ElMessage.warning('请输入有效的仓库路径');
        return;
      }
      
      isLoading.value = true;
      commitHistory.value = [];
      
      try {
        const response = await gitLog(repoPath.value);
        
        if (response.data.success && response.data.data.log_entries) {
          commitHistory.value = response.data.data.log_entries;
        } else if (!response.data.success) {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        ElMessage.error(`获取提交历史失败: ${error.message}`);
        console.error('获取提交历史失败:', error);
      } finally {
        isLoading.value = false;
      }
    };
    
    // 执行克隆操作
    const handleGitClone = async () => {
      if (!cloneForm.url) {
        ElMessage.warning('请输入有效的仓库URL');
        return;
      }
      
      if (!repoPath.value) {
        ElMessage.warning('未设置本地仓库路径，请在项目设置中配置');
        return;
      }
      
      console.log('开始克隆仓库:', {
        repoUrl: cloneForm.url,
        localPath: repoPath.value
      });
      
      isLoading.value = true;
      
      try {
        const response = await gitClone(cloneForm.url, repoPath.value, props.projectId);
        console.log('克隆响应:', response.data);
        showOperationResult('克隆结果', response.data);
        
        // 如果克隆成功，刷新状态
        if (response.data.success) {
          console.log('克隆成功，刷新状态');
          refreshStatus();
          cloneDialogVisible.value = false;
        } else {
          console.error('克隆失败:', response.data.message);
        }
        
        emit('git-operation-completed', {
          operation: 'clone',
          success: response.data.success,
          message: response.data.message
        });
      } catch (error) {
        console.error('Git克隆操作发生异常:', error);
        showOperationResult('克隆结果', {
          success: false,
          message: `克隆失败: ${error.message || '未知错误'}`,
          data: null
        });
      } finally {
        isLoading.value = false;
      }
    };
    
    // 显示操作结果
    const showOperationResult = (title, result) => {
      resultDialogTitle.value = title;
      operationResult.value = result;
      resultDialogVisible.value = true;
    };
    
    // 监听Tab切换
    const handleTabClick = (tab) => {
      if (tab.name === 'branch' && branchList.value.length === 0) {
        loadBranches();
      } else if (tab.name === 'log' && commitHistory.value.length === 0) {
        loadCommitHistory();
      }
    };
    
    // 钩子函数
    onMounted(() => {
      if (repoPath.value) {
        refreshStatus();
      }
      
      // 监听自定义事件，用于父组件触发刷新
      window.addEventListener('git-refresh-status', () => {
        if (repoPath.value) {
          refreshStatus();
        }
      });
    });
    
    // 在组件销毁时移除事件监听
    onUnmounted(() => {
      window.removeEventListener('git-refresh-status', refreshStatus);
    });
    
    return {
      gitUrlDisabled,
      repoPath,
      isLoading,
      statusOutput,
      statusError,
      activeTab,
      branchList,
      selectedBranch,
      branchOutput,
      commitHistory,
      commitDialogVisible,
      resultDialogVisible,
      resultDialogTitle,
      operationResult,
      commitForm,
      commitRules,
      commitFormRef,
      cloneDialogVisible,
      cloneForm,
      cloneFormRef,
      refreshStatus,
      handleGitAddAll,
      showCommitDialog,
      showCloneDialog,
      handleGitCommit,
      handleGitPush,
      handleGitPull,
      loadBranches,
      handleGitCheckout,
      loadCommitHistory,
      handleGitClone,
      showOperationResult,
      handleTabClick
    };
  }
};
</script>

<style scoped>
.git-operations-container {
  margin-bottom: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fff;
}

.git-operations-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.git-operations-header h3 {
  margin: 0;
  font-size: 18px;
}

.repo-path {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 10px;
  width: 100%;
}

.repo-path-tag {
  margin: 0 10px;
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.git-quick-actions {
  margin-bottom: 15px;
}

.git-tabs {
  margin-top: 15px;
}

.git-status, .git-branch, .git-log {
  margin-top: 10px;
  min-height: 200px;
}

.status-output, .branch-output {
  background-color: #f6f8fa;
  padding: 10px;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  max-height: 300px;
  overflow-y: auto;
}

.branch-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.commit-message {
  font-weight: bold;
  margin-bottom: 5px;
}

.commit-details {
  display: flex;
  align-items: center;
  gap: 10px;
}

.commit-author {
  color: #606266;
  font-size: 0.9em;
}

.result-success, .result-error {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.result-icon {
  font-size: 24px;
  margin-right: 10px;
}

.result-icon.success {
  color: #67c23a;
}

.result-icon.error {
  color: #f56c6c;
}

.result-details {
  margin-top: 15px;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.result-stdout, .result-stderr {
  margin-bottom: 10px;
}

.result-stdout pre, .result-stderr pre {
  background-color: #f6f8fa;
  padding: 10px;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  max-height: 200px;
  overflow-y: auto;
}

.result-stderr pre {
  background-color: #fef0f0;
}

.clone-action {
  margin-top: 10px;
}

.dialog-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.2;
}
</style> 